package  main.java.leetcode.editor.cn;
//2022-06-22 23:15:01
//给定一个二叉树的 根节点 root，请找出该二叉树的 最底层 最左边 节点的值。 
//
// 假设二叉树中至少有一个节点。 
//
// 
//
// 示例 1: 
//
// 
//
// 
//输入: root = [2,1,3]
//输出: 1
// 
//
// 示例 2: 
//
// 
//
// 
//输入: [1,2,3,4,null,5,6,null,null,7]
//输出: 7
// 
//
// 
//
// 提示: 
//
// 
// 二叉树的节点个数的范围是 [1,10⁴] 
// -2³¹ <= Node.val <= 2³¹ - 1 
// 
// Related Topics 树 深度优先搜索 广度优先搜索 二叉树 👍 338 👎 0

import java.util.LinkedList;
import java.util.Queue;

class FindBottomLeftTreeValue {
    public static void main(String[] args) {
        //创建该题目的对象方便调用
        Solution solution = new FindBottomLeftTreeValue().new Solution();
        TreeNode root = new TreeNode(0);
        root.left = new TreeNode(1);
        root.right = new TreeNode(2);
        System.out.println(solution.findBottomLeftValue(root));
    }
    public static class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode() {}
        TreeNode(int val) { this.val = val; }
        TreeNode(int val, TreeNode left, TreeNode right) {
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }
    //leetcode submit region begin(Prohibit modification and deletion)
/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
class Solution {
//    int TreeHeight = 0;
//    int val = 0;
    public int findBottomLeftValue(TreeNode root) {
//        dfs(root,1);
//        return val;
        //bfs写法

        if(root == null){
            return 0;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int result = root.val;

        while (!queue.isEmpty()){
            int n = queue.size();
            for (int i = 0;i<n;i++){
                TreeNode node = queue.poll();

                if (node.left != null) {
                    queue.offer(node.left);
                }
                if(node.right != null){
                    queue.offer(node.right);
                }
            }
            if (queue.isEmpty()){
                return result;
            }
            result = queue.peek().val;
        }

        return result;
    }


    /**
    * @author LazyCat
    * @date  2022/10/15
    * @param
    * @return
     * dfs写法
    */
//    public void dfs(TreeNode root,int height){
//        if(root == null){
//            return;
//        }
//        dfs(root.left,height+1);
//        dfs(root.right,height+1);
//        if(height>TreeHeight){
//            TreeHeight = height;
//            val = root.val;
//        }
//
//    }
}
//leetcode submit region end(Prohibit modification and deletion)

}
